package com.ruoyi.system.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.DiyStrategy;
import com.ruoyi.system.domain.Factor;
import com.ruoyi.system.domain.TbDiyStrategyPro;
import com.ruoyi.system.domain.vo.ExcutePythonVo;
import com.ruoyi.system.mapper.FactorCategoryMapper;
import com.ruoyi.system.service.IFactorCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TbDiyStrategyMapper;
import com.ruoyi.system.domain.TbDiyStrategy;
import com.ruoyi.system.service.ITbDiyStrategyService;

/**
 * 策略生成Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-02-16
 */
@Service
public class TbDiyStrategyServiceImpl implements ITbDiyStrategyService 
{
    @Autowired
    private TbDiyStrategyMapper tbDiyStrategyMapper;
    @Autowired
    private FactorCategoryMapper factorCategoryMapper;
    @Autowired
    private IFactorCategoryService factorCategoryService;

    /**
     * 查询策略生成
     * 
     * @param strategyNm 策略生成主键
     * @return 策略生成
     */
    @Override
    public TbDiyStrategy selectTbDiyStrategyByStrategyNm(String strategyNm)
    {
        TbDiyStrategy tbDiyStrategy = tbDiyStrategyMapper.selectTbDiyStrategyByStrategyNm(strategyNm);
//        String s1 = tbDiyStrategy.getStrategyContent();
////        String strategyContent = s1.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
//        tbDiyStrategy.setStrategyContent(strategyContent);
        return tbDiyStrategy;
    }

    /**
     * 查询策略生成列表
     * 
     * @param tbDiyStrategy 策略生成
     * @return 策略生成
     */
    @Override
    public List<TbDiyStrategy> selectTbDiyStrategyList(TbDiyStrategy tbDiyStrategy)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(!user.getUserId().toString().equals("1"))
            tbDiyStrategy.setCreatorId(user.getUserId().toString());
        return tbDiyStrategyMapper.selectTbDiyStrategyList(tbDiyStrategy);
    }

    /**
     * 新增策略生成
     * 
     * @param tbDiyStrategy 策略生成
     * @return 结果
     */
    @Override
    public int insertTbDiyStrategy(TbDiyStrategy tbDiyStrategy)
    {
        return tbDiyStrategyMapper.insertTbDiyStrategy(tbDiyStrategy);
    }

    /**
     * 修改策略生成
     * 
     * @param tbDiyStrategy 策略生成
     * @return 结果
     */
    @Override
    public String updateTbDiyStrategy(TbDiyStrategy tbDiyStrategy)
    {
        tbDiyStrategyMapper.deleteTbDiyStrategyProByStrategyCd(tbDiyStrategy.getStrategyCd());
        DiyStrategy diyStrategy = new DiyStrategy();
        BeanUtils.copyProperties(tbDiyStrategy, diyStrategy);

        if(factorCategoryService.isUseLegal(diyStrategy).equals("数据合法")){
            String s1 = tbDiyStrategy.getStrategyContent();

            String strategyContent = s1.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
            tbDiyStrategy.setStrategyContent(strategyContent);
            tbDiyStrategyMapper.updateTbDiyStrategy(tbDiyStrategy);
            return "修改成功";
        }else {
            return factorCategoryService.isUseLegal(diyStrategy);
        }

    }

    /**
     * 批量删除策略生成
     * 
     * @param strategyNms 需要删除的策略生成主键
     * @return 结果
     */
    @Override
    public int deleteTbDiyStrategyByStrategyNms(String[] strategyNms)
    {


        return tbDiyStrategyMapper.deleteTbDiyStrategyByStrategyNms(strategyNms);
    }

    /**
     * 删除策略生成信息
     * 
     * @param strategyNm 策略生成主键
     * @return 结果
     */
    @Override
    public int deleteTbDiyStrategyByStrategyNm (String strategyNm)
    {
        TbDiyStrategyPro tbDiyStrategyPro=tbDiyStrategyMapper.selectTbDiyStrategyProByStrategyNm(strategyNm);
        String[] cmds = {"/bin/sh","-c","kill -9 "+tbDiyStrategyPro.getProcessId()};
        Process pro = null;
        try {
            pro = Runtime.getRuntime().exec(cmds);
        pro.waitFor();
        InputStream in = pro.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while((line = read.readLine())!=null){
            System.out.println(line);
        }
            return tbDiyStrategyMapper.deleteTbDiyStrategyProByStrategyCd(strategyNm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }


    @Override
    public String executePython(ExcutePythonVo excutePythonVo) {
        try {
            TbDiyStrategy diyStrategy= tbDiyStrategyMapper.selectTbDiyStrategyByStrategyNm(excutePythonVo.getStrategyCd());
            tbDiyStrategyMapper.deleteTbDiyStrategyProByStrategyCd(excutePythonVo.getStrategyCd());
            TbDiyStrategyPro tbDiyStrategyPro=new TbDiyStrategyPro();
            tbDiyStrategyPro.setStrategyCd(diyStrategy.getStrategyCd());
            tbDiyStrategyPro.setIsRun("0");//-1:执行错误，0：准备执行，1：正在执行，2;执行成功
            tbDiyStrategyPro.setCreateTm(DateUtils.getDate());
            tbDiyStrategyPro.setProcessPercent(0);
            if(excutePythonVo.getDateRange().size()!=0){
                tbDiyStrategyPro.setStartTm(excutePythonVo.getDateRange().get(0));
                tbDiyStrategyPro.setStopTTm(excutePythonVo.getDateRange().get(1));
            }

            tbDiyStrategyMapper.insertTbDiyStrategyPro(tbDiyStrategyPro);

//            String pythonPdfPath="/data2/pythondata/fb_stock_calc_hw/StrategySelectionProcess/";
//            String historyDigModu="StrategySelectorPro_Calc.py";
//            //String[] args = new String[]{"python3", "/root/fbstock/stock_pdf_pro/pdf_pro/GuiPro.py", secCd};
//            ArrayList<Object> objects = new ArrayList<>();
//            String[] args = new String[]{"python3", pythonPdfPath + historyDigModu, tbDiyStrategy};
//            //String[] args = new String[]{"C:\\ProgramData\\Anaconda3\\python", pythonPdfPath + historyDigModu, secCd};
//            //String[] args = new String[]{"C:\\ProgramData\\Anaconda3\\python", "D:\\Work\\自主项目\\企业价值分析软件\\PyWork\\stock_pdf_pro\\pdf_pro\\GuiPro.py", secCd};
//            System.out.println("EvalueProServiceImpl::DoPdfPro, secCode: "+ tbDiyStrategy + " path: " + args[1]);
//            Process proc = Runtime.getRuntime().exec(args);
//            proc.waitFor();
        }catch( Exception e){
            e.printStackTrace();
//            log.error("", e);
            return "执行失败";
        }
        return "正在执行，请稍后刷新页面查看！";
    }

    @Override
    public TbDiyStrategyPro selectTbDiyStrategyProByStrategyNm(String ids) {
        return tbDiyStrategyMapper.selectTbDiyStrategyProByStrategyNm(ids);
    }

    @Override
    public int deleteitem() {
        List<Factor> factors=factorCategoryMapper.selectTbDiyItem();
        for(Factor factor:factors){

        }
        if(factors.size()>=2){

        }
        return 1;
    }
}
